package com.db.ionio.serialization;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class ProtobufSerializer implements Serializer<SensorData[]> {
    @Override
    public String getType() {
        return "protobuf";
    }

    @Override
    public void serialize(SensorData[] obj, OutputStream outStream) throws Exception {
        com.db.ionio.serialization.Sensor.SensorBatch.Builder sensorDataBatchBuilder = com.db.ionio.serialization.Sensor.SensorBatch.newBuilder();
        for (SensorData sensorData : obj) {
            sensorDataBatchBuilder.addData(
                    com.db.ionio.serialization.Sensor.SensorBatch.SensorData.newBuilder()
                            .setElevation(sensorData.getElevation())
                            .setLatitude(sensorData.getLatitude())
                            .setLongitude(sensorData.getLongitude())
                            .setTemperature(sensorData.getTemperature())
                            .build()
            );
        }

        sensorDataBatchBuilder.build().writeDelimitedTo(outStream);
    }

    @Override
    public SensorData[] deserialize(InputStream inStream) throws Exception {
        com.db.ionio.serialization.Sensor.SensorBatch sensorDataBatch = com.db.ionio.serialization.Sensor.SensorBatch.parseDelimitedFrom(inStream);
        int length = sensorDataBatch.getDataCount();
        List<SensorData> sensorDataList = new ArrayList<>(length);
        for (com.db.ionio.serialization.Sensor.SensorBatch.SensorData sensorData : sensorDataBatch.getDataList()) {
            sensorDataList.add(new SensorData(sensorData.getLongitude(), sensorData.getLatitude(),
                    sensorData.getElevation(), sensorData.getTemperature()));
        }
        return sensorDataList.toArray(new SensorData[sensorDataList.size()]);
    }
}
